package com.ruoyi.common.utils.pdf;

import com.aspose.words.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * WORD to PDF
 */
@Slf4j
public class AsposeUtil {

    /*
    *加载License 用于破解 不生成印
    * @author LCheng
    */
    /*@SneakyThrows
    public static void getLicense() {
        try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            log.error("--->error:", e);
        }
    }*/

    public static boolean getLicense() {
        boolean result = false;
        try {
            // 凭证
            String licenseStr =
                    "<License>\n" +
                            "  <Data>\n" +
                            "    <Products>\n" +
                            "      <Product>Aspose.Total for Java</Product>\n" +
                            "      <Product>Aspose.Words for Java</Product>\n" +
                            "    </Products>\n" +
                            "    <EditionType>Enterprise</EditionType>\n" +
                            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                            "  </Data>\n" +
                            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                            "</License>";
            InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            log.error("error:", e);
        }
        return result;
    }


    @SneakyThrows
    public static void wordTopdf (String wordPath, String pdfpath, String fontFamilyPath) {
        getLicense();
        File file = new File(pdfpath);
        try (FileOutputStream os = new FileOutputStream(file)) {

            if (File.separator.equals("/")) {
                //解决Linux下字体问题
                //log.info("fontFamilyPath:{}", fontFamilyPath);
                FontSettings.setFontsFolder(fontFamilyPath, true);
            }
            Document doc = new Document(wordPath);
            doc.save(os, SaveFormat.PDF);
        }
    }
}
